<?php
// cms前台
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2017 http://www.eacoo123.com, All rights reserved.         
// +----------------------------------------------------------------------
// | [EacooPHP] 并不是自由软件,可免费使用,未经许可不能去掉EacooPHP相关版权。
// | 禁止在EacooPHP整体或任何部分基础上发展任何派生、修改或第三方版本用于重新分发
// +----------------------------------------------------------------------
// | Author:  心云间、凝听 <981248356@qq.com>
// +----------------------------------------------------------------------
namespace app\cms\controller;
use app\common\model\User;
use app\home\controller\Home;

use app\cms\model\Posts as PostsModel;
use app\cms\logic\Category as CategoryLogic;
use app\common\model\Terms as TermsModel;
use app\cms\logic\Tag as TagLogic;
use app\cms\model\Postmeta as PostmetaModel;
use app\home\model\Focus;


class Index extends Home {

    protected $postModel;
    protected $termsModel;
	function _initialize()
    {
        parent::_initialize();

        $this->postModel  = new PostsModel();
        $this->termsModel = new TermsModel();
        $this->assign('category_list',CategoryLogic::getCategories());
        $this->assign('tag_list',TagLogic::getTags());
    }   

    /**
     * 首页
     */
    public function index() {

        $this->pageInfo('首页','index');
        
        $map = [
            'status' =>1,
            'type'   =>'post'
        ];
        //分类筛选
        $cat_id = input('param.cat_id');
        if ($cat_id>0) {
            $cat_post_ids = db('term_relationships')->where(['term_id'=>$cat_id])->column('object_id');
            if(!empty($cat_post_ids)) $map['id']=['in',$cat_post_ids];
        }
        //标签筛选
        $tag_id = input('param.tag_id');
        if ($tag_id>0) {
            $tag_post_ids = db('term_relationships')->where(['term_id'=>$tag_id])->column('object_id');
            if(!empty($tag_post_ids)){
                $map['id']=['in',$tag_post_ids];
            } elseif (empty($map['id'])) {
                $map['id']='';
            }
        }
        if (!empty($cat_post_ids) && !empty($tag_post_ids)) {
            $ids = array_unique(array_merge($cat_post_ids,$tag_post_ids));
            $map['id']=['in',$ids];
        }
        $post_list = PostsModel::where($map)->order('sort desc,create_time desc,id desc')->paginate(15);

        $this->assign('post_list',$post_list);
        $this->assign('pageTitle','文章列表');
        return $this->fetch();
    }

    /**
     * 获取详情
     * @param  integer $id [description]
     * @return [type] [description]
     * @date   2017-10-16
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function detail($id=0)
    {
        $info = PostsModel::get($id);

        $this->pageInfo($info['title'],'detail');
        $user=\app\common\logic\User::info($info['author_id']);
        //$user = $info->getAuthorAttr('',$info);
        $this->assign('info',$info);
        $this->assign('pageTitle',$info->title);
        $this->assign('user',$user);
        return $this->fetch();
    }

    /**
     * 新增或编辑
     * @param  integer $id [description]
     * @return [type] [description]
     * @date   2017-10-15
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function edit($id = 0){

        $title = $id>0 ? "编辑":"新增"; 
        
        //修改
        if(IS_POST){
            $data = $this->request->param();
    
            $data['author_id']    = is_login();
            $data['type']         = 'post';
            $data['content']      = htmlspecialchars_decode($data['content']);
            //$data['fields']     =input('fields');
            
            //验证数据
            $this->validateData($data,'Post.edit');
            $result = $this->postModel->editData($data);
            if($result){
                $postmeta = input('param.postmeta/a');
                if (!empty($postmeta)) {
                    $post_meta_model = new PostmetaModel;
                    $meta_keys = $post_meta_model->where('post_id',$id)->column('meta_key');
                     /* 提交过来的 跟数据库中比较 不存在 删除*/
                     $del_metas = [];
                     $postmeta_keys = array_column($postmeta,'meta_key');
                     if (!empty($meta_keys)) {
                         foreach ($meta_keys as $key => $value) {
                            if(!in_array($value,$postmeta_keys)) $del_metas[] = $value; 
                        }
                     }
                     //这是元数据
                    foreach ($postmeta as $key => $val) {
                        if (!empty($val['meta_value'])) {
                            $post_meta_model->setMeta($id,$val['meta_key'],$val['meta_value']);
                        }
                        
                    }
                    //删除不存在的
                    foreach ($del_metas as $key => $value) {
                        $post_meta_model->deleteMeta($id,$value);
                    }
                }
                update_post_term($id,input('post.category_id',false));
                $this ->success($title.'成功','');
            } else{
                $this ->error($this->postModel->getError());
            }

        } else{
            $this->assign('page_config',['disable_panel'=>true,'back'=>true]);
            $this->assign('meta_title',$title.'文章');

            $info = [
                'content'=>'',
                'img'=>''
            ];
            if ($id>0) {
                $info = PostsModel::get($id);
                $this->assign('category_id',get_the_category($id));
                $this->assign('tag_ids',get_the_category($id));
                $this->assign('meta_list',PostmetaModel::getMetas($id));
            } else {
                $this->assign('category_id',0);
                $this->assign('tag_ids',0);
            }
            $this->assign('info',$info);
            
            $this->assign('form_url',url('edit',['id'=>$id]));

            $this->assign('post_category',logic('Category')->getOptTerms('post_category'));
            $this->assign('post_tags',logic('Category')->getOptTerms('post_tag'));
            $this->assign('tag_id',1);//测试
            return $this->fetch();
        }
        
    }

    public function focus($post_id) {

        $focusModel = new Focus();
        if(is_login())
        {
            //如果登录
            $focusModel->uid_a = session('uid');
        }else
        {
            $this->success('请先登录，正在跳转!','index.php/home/Index/index');
        }
       
        $focusModel->post_id=$post_id;
        if($op==1)
        {         
            if($focusModel->save()==1)
            {
                $this->success("收藏成功，正在跳转!");
            }
            else{
                $this->error("收藏失败，正在跳转!");
            }
        }
        else
        {
            $focus=$focusModel->where('uid_a',session('uid'))->where('post_id',$post_id)->find();
            $idd=$focus['id'];
            $focus = Focus::get($idd);
            if($focus->delete()==1)
            {
                $this->success("取消成功，正在跳转!");
            }
            else
            {
                $this->error("取消失败，正在跳转!");
            }
        }
        
    }
 


}